package com.yupi.picturebackend.api.examine;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import com.yupi.picturebackend.api.examine.model.ImageModerationResponse;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class TengXunApi {
    @Resource
    private COSClient cosClient;

    @Value("${cos.client.bucket}")
    private String BUCKET_NAME;

    /**
     * 审核图片
     * @param url
     */
    public ImageModerationResponse checkPicture(String url) {
        log.info("腾讯云审核图片：{}", url);
        //1.创建任务请求对象
        ImageAuditingRequest request = new ImageAuditingRequest();
        //2.添加请求参数
        request.setBucketName(BUCKET_NAME); //存储桶名称
        request.setDetectUrl(url);             //图片链接
        request.setBizType("");               //审核策略
        //3.调用接口,获取任务响应对象
        ImageAuditingResponse response = cosClient.imageAuditing(request);
        //4.获取任务结果
        if (!response.getState().equals("Success")){
            log.info("审核功能出问题了");
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"审核功能出问题了");
        }
        String result = response.getResult();// 0（审核正常），1 （判定为违规敏感文件），2（疑似敏感，建议人工复核）
        if (Integer.valueOf(result) > 2 || Integer.valueOf(result) < 0){
            log.info("审核功能出问题了,返回什么几把");
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"审核功能出问题了,返回什么几把");
        }
        //5.构造返回结果
        ImageModerationResponse imageModerationResponse = new ImageModerationResponse();
        imageModerationResponse.setResult(result);
        switch (result){
            case "0":
                imageModerationResponse.setMessage("审核通过");
                break;
            case "1":
                imageModerationResponse.setMessage("图片中存在违规信息");
                break;
            case "2":
                imageModerationResponse.setMessage("疑似敏感，建议人工复核");
                break;
            default:
                imageModerationResponse.setMessage("未知");
                break;
        }
        return imageModerationResponse;
    }
}
